﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Xml;
using Taobao.Top.Api;
using Taobao.Top.Api.Request;
using Taobao.Top.Api.Domain;
using Common;

public partial class top_review_testapi : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GetTradeWuliu();
    }

    private void GetCustomerList()
    {
        string result = string.Empty;
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string taobaonick = "mildseven006";
        string sql = string.Empty;
        string session = string.Empty;

        sql = "SELECT session FROM TCS_ShopSession WHERE nick = '" + taobaonick + "'";
        session = utils.ExecuteString(sql);

        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("page_size", "100");
        param.Add("current_page", "1");
        param.Add("relation_source", "1");
        param.Add("order", "lastest_time");
        param.Add("sort", "desc");

        result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.members.search", session, param);
        Response.Write(result + "\r\n\r\n");
    }

    private void GetOrderShippingInfo()
    {
        string result = string.Empty;
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string taobaonick = "廖福权";
        string sql = string.Empty;
        string session = string.Empty;
        string orderid = "204345386568296";

        sql = "SELECT session FROM TCS_ShopSession WHERE nick = '" + taobaonick + "'";
        session = utils.ExecuteString(sql);

        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("tid", orderid);
        param.Add("fields", "out_sid, company_name");

        result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.logistics.orders.detail.get", session, param);
        Response.Write(result + "\r\n\r\n");
    }

    private void GetShippingStatus()
    {
        string result = string.Empty;
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string taobaonick = "咕噜小哈尼";
        string sql = string.Empty;
        string session = string.Empty;
        string orderid = "208208139893990";

        sql = "SELECT session FROM TCS_ShopSession WHERE nick = '" + taobaonick + "'";
        session = utils.ExecuteString(sql);

        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("fields", "delivery_start,delivery_end,status");
        param.Add("tid", orderid);

        result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.logistics.orders.get", session, param);
        Response.Write(result + "\r\n\r\n");
    }

    private void GetGroupInfo()
    {
        string result = string.Empty;
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string taobaonick = "香香精品店001";
        string sql = string.Empty;
        string session = string.Empty;

        sql = "SELECT session FROM TCS_ShopSession WHERE nick = '" + taobaonick + "'";
        session = utils.ExecuteString(sql);

        IDictionary<string, string> param = new Dictionary<string, string>();

        result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.grade.get", session, param);
        Response.Write(result + "\r\n\r\n");
    }

    private void GetLostMessage()
    {
        string result = string.Empty;
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";

        string sql = string.Empty;
        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("types", "trade");
        param.Add("start", "2013-04-02 13:13:00");
        param.Add("end", "2013-04-02 13:17:00");

        result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.comet.discardinfo.get", "", param);
        //Response.Write(result + "\r\n\r\n");

        Regex reg = new Regex(@"<discard_info>([\s\S]*?)</discard_info>");
        MatchCollection match = reg.Matches(result);
        Response.Write(result + "--" + match.Count + "\r\n\r\n");
    }

    private void GetTradeWuliuByOrder()
    {
        string result = string.Empty;
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string session = "61008206a3b36bd4ab34807524191b6b812836a311dec8b665592665";
        string taobaonick = "amdyygy";
        string orderid = "328860885142001";

        string sql = string.Empty;

        sql = "SELECT session FROM TCS_ShopSession WHERE nick = '" + taobaonick + "'";
        session = utils.ExecuteString(sql);

        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("seller_nick", taobaonick);
        param.Add("tid", orderid);

        result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.logistics.trace.search", session, param);
        Response.Write(result + "\r\n\r\n");
    }

    private void GetTradeWuliu()
    {
        string result = string.Empty;
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string session = "61008206a3b36bd4ab34807524191b6b812836a311dec8b665592665";
        string taobaonick = "江南绿萝";

        string sql = "GetShippingShopTrade '" + taobaonick + "' ";
        DataTable dt = utils.ExecuteDataTable(sql);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            sql = "SELECT session FROM TCS_ShopSession WHERE nick = '" + dt.Rows[i]["nick"].ToString() + "'";
            session = utils.ExecuteString(sql);

            IDictionary<string, string> param = new Dictionary<string, string>();
            param.Add("seller_nick", dt.Rows[i]["nick"].ToString());
            param.Add("tid", dt.Rows[i]["orderid"].ToString());

            result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.logistics.trace.search", session, param);
            Response.Write(result + "\r\n\r\n");

            //是否评价
            param = new Dictionary<string, string>();
            param.Add("fields", "receiver_mobile, orders.num_iid, created, consign_time, total_fee, payment, promotion_details, type, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, status, buyer_area, orders.oid, orders.refund_id, payment, buyer_rate");
            param.Add("tid", dt.Rows[i]["orderid"].ToString());
            result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.trade.fullinfo.get", session, param);
            Response.Write(result + "\r\n\r\n");
        }
    }

    private void GetUserCoupon()
    {
        string result = string.Empty;
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string buynick = "ahaqyj";
        string taobaonick = "沙漏的舞蹈55208";
        string session = "6101503745f1265a20262d5e8288968fa2c4e3871eea348679089675";

        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("coupon_id", "14190504");
        param.Add("state", "unused");
        param.Add("page_no", "1");
        param.Add("page_size", "20");
        param.Add("end_time", "2012-11-08 00:00:00");
        //param.Add("buyer_nick", buynick);
        result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.promotion.coupondetail.get", session, param);
        Response.Write(result);
    }

    private void GetTradeRate()
    {
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";

        string taobaonick = "huangqinyi2006";
        string result = string.Empty;

        string sql = "SELECT session FROM TCS_ShopSession WHERE nick = '" + taobaonick + "'";
        string session = utils.ExecuteString(sql);

        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("fields", "content,created,nick,result");
        param.Add("rate_type", "get");
        param.Add("role", "buyer");
        param.Add("tid", "212281132117937");
        result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.traderates.get", session, param);
        Response.Write(result);
    }

    private void GetTrade()
    {
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string sql = string.Empty;
        string session = "6101a08f02ccda601a9ae3d454494eb1b534dfddd2d8743748642333";
        string taobaonick = "huangqinyi2006";

        IDictionary<string, string> param = new Dictionary<string, string>();

        sql = "SELECT session FROM TCS_ShopSession WHERE nick = '" + taobaonick + "'";
        session = utils.ExecuteString(sql);

        param.Add("fields", "receiver_mobile, orders.num_iid, created, consign_time, total_fee, payment, promotion_details, type, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, status, buyer_area, orders.oid, orders.refund_id, payment, buyer_rate");
        param.Add("tid", "212281132117937");

        string result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.trade.fullinfo.get", session, param);

        Response.Write(result);
    }

    public void GetFahuoMsg()
    {
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string session = "6101a08f02ccda601a9ae3d454494eb1b534dfddd2d8743748642333";
        string nick = "世星运动专营店";
        string typ = "TradeSellerShip";
        string result = string.Empty;
        string date = "2013-04-01";

        string sql = "SELECT * FROM TCS_ShopSession WHERE nick = '" + nick + "'";
        DataTable dt = utils.ExecuteDataTable(sql);
        if (dt.Rows.Count != 0)
        {
            for (int i = 1; i < 200; i++)
            {
                IDictionary<string, string> param = new Dictionary<string, string>();
                param.Add("status", typ);
                param.Add("nick", nick);
                param.Add("start_modified", date + " 00:00:00");
                param.Add("end_modified", date + " 23:59:59");
                param.Add("page_no", i.ToString());
                param.Add("page_size", "200");
                result = PostJson("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.increment.trades.get", session, param);
                Response.Write(result + "\r\n");

                Regex reg1 = new Regex(@"\{""buyer_nick""[^\}]*\}", RegexOptions.IgnoreCase);
                MatchCollection match1 = reg1.Matches(result);
                for (int k = 0; k < match1.Count; k++)
                {
                    string resultNew = "\"msg\":{\"notify_trade\":" + match1[k].Groups[0].ToString() + "}";
                    InsertMsgLogInfo(nick, typ, resultNew);
                }

                if (match1.Count < 200)
                {
                    break;
                }
            }
        }
    }

    public void InsertMsgLogInfo(string nick, string typ, string result)
    {
        string sql = "INSERT INTO TCS_TaobaoMsgLog (" +
                            "nick, " +
                            "typ, " +
                            "result " +
                        " ) VALUES ( " +
                            " '" + nick + "', " +
                            " '" + typ + "', " +
                            " '" + result + "' " +
                        ") ";
        Response.Write(sql + "<br>");
        //utils.ExecuteNonQuery(sql);
    }

    private void ReflashSession(string nick)
    {
        IDictionary<string, string> param = new Dictionary<string, string>();
        string url = string.Empty;
        string result = string.Empty;
        string str = string.Empty;
        string sign = string.Empty;
        string sql = "SELECT * FROM TCS_ShopSession WHERE token <> '' AND version > 1 AND nick = '" + nick + "'";
        DataTable dt = utils.ExecuteDataTable(sql);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            try
            {
                sign = CreateSign("12159997", "614e40bfdb96e9063031d1a9e56fbed5", dt.Rows[i]["token"].ToString(), dt.Rows[i]["session"].ToString());

                url = "http://container.open.taobao.com/container/refresh?appkey=12159997&refresh_token=" + dt.Rows[i]["token"].ToString() + "&sessionkey=" + dt.Rows[i]["session"].ToString() + "&sign=" + sign;
                result = Post(url);
                Response.Write(url + "<br>");
                Response.Write(result);
            }
            catch { }
        }
    }


    public string Post(string url)
    {
        string result = string.Empty;
        #region ---- 完成 HTTP POST 请求----
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "GET";
        req.KeepAlive = true;
        req.Timeout = 300000;
        HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
        Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
        Stream stream = null;
        StreamReader reader = null;
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        result = reader.ReadToEnd();
        if (reader != null) reader.Close();
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
        #endregion
        return Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", "");
    }

    protected static string CreateSign(string appkey, string app_secret, string token, string session)
    {
        StringBuilder result = new StringBuilder();
        System.Security.Cryptography.MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        result.Append("appkey").Append(appkey).Append("refresh_token").Append(token).Append("sessionkey").Append(session).Append(app_secret);
        byte[] bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(result.ToString()));

        result.Remove(0, result.Length);
        for (int i = 0; i < bytes.Length; i++)
        {
            string hex = bytes[i].ToString("X");
            if (hex.Length == 1)
            {
                result.Append("0");
            }
            result.Append(hex);
        }

        return result.ToString();
    }

    private void GetTradeList()
    {
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string sql = string.Empty;
        string session = "6101a08f02ccda601a9ae3d454494eb1b534dfddd2d8743748642333";
        string taobaonick = "小皇帝旗舰店";

        IDictionary<string, string> param = new Dictionary<string, string>();

        sql = "SELECT session FROM TCS_ShopSession WHERE nick = '" + taobaonick + "'";
        session = utils.ExecuteString(sql);

        param.Add("fields", "buyer_nick,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_mobile");
        param.Add("buyer_nick", "rgd_001");
        param.Add("page_no", "1");
        param.Add("page_size", "100");
        //param.Add("start_created", "2012-03-01 00:00:00");
        //param.Add("end_created", "2012-03-26 00:00:00");

        string result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.trades.sold.get", session, param);

        Response.Write(result);
    }


    private void Fresh()
    {
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";

        string session = "6102a28c7dc9ad3f71b1c98c7708502a228316b5bdb250414732390";
        string taobaonick = "tangchao4010790";

        IDictionary<string, string> param = new Dictionary<string, string>();

        param.Add("fields", "id,code,name,reg_mail_no");

        string result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.logistics.companies.get", session, param);
        ////<coupon_number>1323930538</coupon_number>
        //Response.Write(result + "<br>");
        Regex reg = new Regex(@"<code>([^<]*)</code><id>([^<]*)</id><name>([^<]*)</name>", RegexOptions.IgnoreCase);
        MatchCollection match = reg.Matches(result);

        for (int i = 0; i < match.Count; i++)
        {
            string sql = "SELECT COUNT(*) FROM TCS_TaobaoShippingCompany WHERE short = '" + match[i].Groups[1].ToString() + "'";
            string count = utils.ExecuteString(sql);

            if (count == "0")
            {
                if (match[i].Groups[1].ToString() != "OTHER" && match[i].Groups[1].ToString() != "POST")
                {
                    sql = "INSERT INTO TCS_TaobaoShippingCompany (name, short) VALUES ('" + match[i].Groups[3].ToString() + "', '" + match[i].Groups[1].ToString() + "')";
                    Response.Write(sql + "<br>");
                    utils.ExecuteNonQuery(sql);
                }
            }
            else
            {
                sql = "UPDATE TCS_TaobaoShippingCompany SET name = '" + match[i].Groups[3].ToString() + "' WHERE short = '" + match[i].Groups[1].ToString() + "'";
                Response.Write(sql + "<br>");
                utils.ExecuteNonQuery(sql);
            }
        }
    }


    #region TOP API
    /// <summary> 
    /// 给TOP请求签名 API v2.0 
    /// </summary> 
    /// <param name="parameters">所有字符型的TOP请求参数</param> 
    /// <param name="secret">签名密钥</param> 
    /// <returns>签名</returns> 
    protected static string CreateSign(IDictionary<string, string> parameters, string secret)
    {
        parameters.Remove("sign");
        IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
        IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
        StringBuilder query = new StringBuilder(secret);
        while (dem.MoveNext())
        {
            string key = dem.Current.Key;
            string value = dem.Current.Value;
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
            {
                query.Append(key).Append(value);
            }
        }
        query.Append(secret);
        MD5 md5 = MD5.Create();
        byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
            string hex = bytes[i].ToString("X");
            if (hex.Length == 1)
            {
                result.Append("0");
            }
            result.Append(hex);
        }
        return result.ToString();
    }
    /// <summary> 
    /// 组装普通文本请求参数。 
    /// </summary> 
    /// <param name="parameters">Key-Value形式请求参数字典</param> 
    /// <returns>URL编码后的请求数据</returns> 
    protected static string PostData(IDictionary<string, string> parameters)
    {
        StringBuilder postData = new StringBuilder();
        bool hasParam = false;
        IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
        while (dem.MoveNext())
        {
            string name = dem.Current.Key;
            string value = dem.Current.Value;
            // 忽略参数名或参数值为空的参数 
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
            {
                if (hasParam)
                {
                    postData.Append("&");
                }
                postData.Append(name);
                postData.Append("=");
                postData.Append(Uri.EscapeDataString(value));
                hasParam = true;
            }
        }
        return postData.ToString();
    }
    /// <summary> 
    /// TOP API POST 请求 
    /// </summary> 
    /// <param name="url">请求容器URL</param> 
    /// <param name="appkey">AppKey</param> 
    /// <param name="appSecret">AppSecret</param> 
    /// <param name="method">API接口方法名</param> 
    /// <param name="session">调用私有的sessionkey</param> 
    /// <param name="param">请求参数</param> 
    /// <returns>返回字符串</returns> 
    public static string Post(string url, string appkey, string appSecret, string method, string session,
    IDictionary<string, string> param)
    {
        #region -----API系统参数----
        param.Add("app_key", appkey);
        param.Add("method", method);
        param.Add("session", session);
        param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        param.Add("format", "xml");
        param.Add("v", "2.0");
        param.Add("sign_method", "md5");
        param.Add("sign", CreateSign(param, appSecret));
        #endregion
        string result = string.Empty;
        #region ---- 完成 HTTP POST 请求----
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.KeepAlive = true;
        req.Timeout = 300000;
        req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
        byte[] postData = Encoding.UTF8.GetBytes(PostData(param));
        Stream reqStream = req.GetRequestStream();
        reqStream.Write(postData, 0, postData.Length);
        reqStream.Close();
        HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
        Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
        Stream stream = null;
        StreamReader reader = null;
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        result = reader.ReadToEnd();
        if (reader != null) reader.Close();
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
        #endregion
        return Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", "");
    }
    /// <summary> 
    /// TOP API POST 请求 
    /// </summary> 
    /// <param name="url">请求容器URL</param> 
    /// <param name="appkey">AppKey</param> 
    /// <param name="appSecret">AppSecret</param> 
    /// <param name="method">API接口方法名</param> 
    /// <param name="session">调用私有的sessionkey</param> 
    /// <param name="param">请求参数</param> 
    /// <returns>返回字符串</returns> 
    public static string PostJson(string url, string appkey, string appSecret, string method, string session,
    IDictionary<string, string> param)
    {
        #region -----API系统参数----
        param.Add("app_key", appkey);
        param.Add("method", method);
        param.Add("session", session);
        param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        param.Add("format", "json");
        param.Add("v", "2.0");
        param.Add("sign_method", "md5");
        param.Add("sign", CreateSign(param, appSecret));
        #endregion
        string result = string.Empty;
        #region ---- 完成 HTTP POST 请求----
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.KeepAlive = true;
        req.Timeout = 300000;
        req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
        byte[] postData = Encoding.UTF8.GetBytes(PostData(param));
        Stream reqStream = req.GetRequestStream();
        reqStream.Write(postData, 0, postData.Length);
        reqStream.Close();
        HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
        Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
        Stream stream = null;
        StreamReader reader = null;
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        result = reader.ReadToEnd();
        if (reader != null) reader.Close();
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
        #endregion
        return Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", "");
    }
    #endregion
}